const fs = require('fs')
const tours = JSON.parse(
  fs.readFileSync(
    `${__dirname}/../dev-data/data/tours-simple.json`
  )
)

exports.checkID = (req, res, next, val) => {
  console.log(`val is: ${val}`)
  if (+val > tours.length) {
    return res.status(404).json({
      status: 'fail',
      message: 'Invalid ID',
    })
  }
  next()
}

exports.createTour = (req, res) => {
  // 从数据列表中获取最后一条数据的id 再加1
  let newId = tours[tours.length - 1].id + 1
  const newTours = Object.assign({ id: newId }, req.body)
  tours.push(newTours) // 添加到数据最后一条中
  // 写入数据中
  fs.writeFile(
    './dev-data/data/tours-simple.json',
    JSON.stringify(tours),
    (err) => {
      console.log('写入数据完成!')
    }
  )

  res.status(200).json({
    status: 'success',
    data: {
      tours: newTours,
    },
  })
}

exports.getAllTours = (req, res) => {
  res.status(200).json({
    status: 'success',
    count: tours.length,
    requestAt: req.requestTime,
    data: {
      tours,
    },
  })
}

exports.getTour = (req, res) => {
  const tour = tours.find((el) => el.id === +req.params.id)
  console.log(tour)
  if (!tour) {
    return res.status(404).json({
      status: 'fail',
      message: 'Invalid ID',
    })
  }

  res.status(200).json({
    messeage: 'success',
    data: tour,
  })
}

exports.updateTour = (req, res) => {
  res.status(200).json({
    status: 'success',
    data: 'update is here....',
  })
}

exports.deleteTour = (req, res) => {
  res.status(201).json({
    status: 'success',
    data: 'null',
  })
}
